// pages/game/game.js
const playersStore = require('../../stores/players')
const recordsStore = require('../../stores/records')
const STORAGE_KEYS = require('../../configs/STORAGE_KEYS')
const { getRoundInfo, getNextRecord } = require('../../business/records')
const { calcFinalPoints } = require('../../business/calcPoints')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentPlayerNums: [],
    records: [],
    finalPoints: [],
    nextRoundInfo: '',
    leftStickNum: 0,
    currentPlayers: [],
    orderOptions: [{
      value: 'normal',
      label: '顺'
    }, {
      value: 'reverse',
      label: '逆'
    }],
    order: 'normal',
    // 展示结算页面
    showResult: false,
  },

  onLoad() {
    console.log('onLoad')
    this.init();
    recordsStore.addConnector(() => {
      this.init();
    })
  },

  init() {
    // 设置从缓存中获取的数据
    this.setDataFromStore();
    // 设置下一局信息
    this.setNextRoundInfo();
    // 设置当前得点分数，并会同时设置剩余点棒数
    this.setFinalPoints();
    this.setCurrentPlayers();
  },

  setDataFromStore() {
    const currentPlayerNums = wx.getStorageSync(STORAGE_KEYS.CURRENT_PLAYER_NUMS) || [];
    const records = recordsStore.getCurrentGameRecords();
    this.setData({ currentPlayerNums, records })
  },

  setNextRoundInfo() {
    const { records } = this.data;
    const lastRecord = records[records.length - 1];
    const nextRecord = getNextRecord(lastRecord);
    const nextRoundInfo = getRoundInfo(nextRecord);
    this.setData({
      nextRoundInfo,
    })
  },

  setFinalPoints() {
    const { records } = this.data;
    const { finalPoints, leftStickNum } = calcFinalPoints(records)
    this.setData({ finalPoints, leftStickNum })
  },

  setCurrentPlayers() {
    const { currentPlayerNums } = this.data;
    const allPlayers = playersStore.getPlayers()
    const currentPlayers = [0, 0, 0, 0].map((v, i) => this.getPlayerByNum(allPlayers, currentPlayerNums[i], i));
    this.setData({
      currentPlayers,
    })
  },

  getPlayerByNum(players, playerNum, index) {
    const currentPlayer = players[playerNum];
    let player;
    const point = this.data.finalPoints[index];
    if (currentPlayer) {
      player = { nickname: currentPlayer.nickname, playerNum: currentPlayer.playerNum, point, key: index }
    } else {
      player = { nickname: '匿名', playerNum: undefined, point, key: index }
    }
    return player;
  },

  hanldeAddOneRound() {
    wx.navigateTo({
      url: '/pages/round/round',
    })
  },

  // 结束对局并进行结算
  handleOver() {
    this.setData({ showResult: true })
  },

  handleCloseOver() {
    this.setData({ showResult: false })
  }

})